#include "data.hpp"

#include "disk.hpp"

static const char *DIR = "dat/";
static const char *EXT = ".js";

bool Data::Open(const char *name)
{
	std::string path;
	path += DIR;
	path += name;
	path += EXT;
	return FOpen(path);
}

bool Data::FOpen(const char *path)
{
	std::string text;
	int readct = Dsk.TextOpen(path, text);
	if (readct <= 0)
		return false;

	return Parse(text.c_str());
}

bool Data::Parse(const char *text)
{
	json = cJSON_Parse(text);
	return json != NULL;
}

#include <stdlib.h>

bool Data::Save(const char *name)
{
	char *rawtext = cJSON_Print(json);
	std::string text (rawtext);
	free(rawtext); // allocated with malloc(), not new

	std::string path;
	path += DIR;
	path += name;
	path += EXT;
	
	Dsk.SaveToBase();
	int writect = Dsk.TextSave(path, text);

	return writect > 0 && (unsigned)writect == text.size();
}

void Data::Close()
{
	cJSON_Delete(json);
}

Data Data::InsAfter(Data it, const char *dname, Data d)
{
	if (!d)
		return Data();

	if (it)
	{
		if (it.json->next)
			it.json->next->prev = d.json;
		d.json->next = it.json->next;
		d.json->prev = it.json;
		it.json->next = d.json;
	}
	else
	{
		if (json->child)
			json->child->prev = d.json;
		d.json->next = json->child;
		json->child = d.json;
	}

	if (dname)
	{
		size_t len = std::strlen(dname) + 1;
		free(d.json->string);
		d.json->string = (char*)malloc(len);
		std::memcpy(d.json->string, dname, len);
	}

	return d;
}
